import { exec } from 'child_process';
import { ModuleMetadata } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { NestFastifyApplication, FastifyAdapter } from '@nestjs/platform-fastify';
import fastify from 'fastify';
import metricsPlugin from 'fastify-metrics';

import {
    EnvironmentParameters,
    EnvironmentType,
    getEnvironmentValue,
    setEnvironmentValue,
} from '@libs/common/environment';

import { BootstrapOptions } from './bootstrap.interfaces';
import { CommonExceptionFilter } from '../filters/error-filters';

export default async function bootstrap(module: ModuleMetadata, options?: BootstrapOptions) {
    const fastifyInstance = fastify({
        ignoreTrailingSlash: true,
        caseSensitive: false,
        logger: true,
    });

    fastifyInstance.register(metricsPlugin, { endpoint: '/metrics' });

    fastifyInstance.addHook('onSend', (request, reply, payload, done) => {
        reply.header('s-site-id', 'default');
        done(undefined, payload);
    });

    const isProd = getEnvironmentValue('NODE_ENV') === EnvironmentType.prd;

    setEnvironmentValue(
        EnvironmentParameters.RUN_ENV,
        isProd ? EnvironmentType.prd : EnvironmentType.dev,
    );
    setEnvironmentValue(EnvironmentParameters.ROOT_PATH, options?.rootDir);

    // must call when set RUN_ENV & ROOT_PATH
    // const configCenter = new ConfigCenter();

    const app = await NestFactory.create<NestFastifyApplication>(module, new FastifyAdapter());

    // use global
    app.useGlobalFilters(new CommonExceptionFilter(!isProd));

    const port = options?.port ?? 8231;

    // default is 127.0.0.1,if want be reach by others, need set host to 0.0.0.0,
    // refer to:https://www.fastify.io/docs/latest/Getting-Started/#your-first-server or https://docs.nestjs.cn/6/techniques?id=%e6%80%a7%e8%83%bd%ef%bc%88fastify%ef%bc%89
    // 0.0.0.0::
    //await app.listen(port, '0.0.0.0', (err, address) => {
    await app.listen(port, '0.0.0.0', (err, address) => {
        if (err) {
            console.log('start server error');
            console.log(err.message);

            fastifyInstance.log.error(err);
            process.exit(1);
        } else {
            console.log('env:', getEnvironmentValue(EnvironmentParameters.RUN_ENV));
            console.log('rootPath:', getEnvironmentValue(EnvironmentParameters.ROOT_PATH));

            console.log(`server are running on ${address} now.`);
        }
    });
}
